// pages/index/bikeInfo/bikeInfo.js
import api from '../../../config/api'
import path from '../../../config/path'
import baseMessage from '../../../config/message'
const app = getApp()
const { $Message } = require('../../../dist/base/index');
const { $Toast } = require('../../../dist/base/index');

Page({
  data: {
    rentVisiable: false,
    rentType: 'long', // 默认长租
    rentTypes: [
      { name: '长租(按月)', value: 'long' },
      { name: '短租(按小时)', value: 'short' }
    ],
    // 长租相关
    startMonth: '',
    endMonth: '',
    // 短租相关
    startDate: '',
    startTime: '',
    endDate: '',
    endTime: '',
    minDate: new Date().toISOString().split('T')[0],
    maxDate: new Date(new Date().setFullYear(new Date().getFullYear() + 1)).toISOString().split('T')[0],
    rentError: '',
    // 其他原有数据
    collectionInfo: {},
    collection: false,
    markers: [{
      id: 1,
      iconPath: "../../../images/icon/location.png",
      height: 34,
      latitude: 23.099994,
      longitude: 113.324520,
    }],
    picLocal: app.globalData.picLocal,
    id: '',
    imageSetting: {
      indicatorDots: true,
      autoplay: true,
      interval: 5000,
      duration: 500
    },
    bikeResource: {},
    owner: {},
    baseHeadPic: app.globalData.picLocal + "/default/head/head.png",
    showModal: false,
    viewTime: '',
    viewDate: ''
  },

  onLoad: function (options) {
    this.setData({ id: options.id });
    this.loadBikeInfo();
    
    // 设置默认日期
    const today = new Date();
    const defaultDate = `${today.getFullYear()}-${(today.getMonth()+1).toString().padStart(2, '0')}-${today.getDate().toString().padStart(2, '0')}`;
    const defaultMonth = `${today.getFullYear()}-${(today.getMonth()+1).toString().padStart(2, '0')}`;
    
    this.setData({
      viewDate: defaultDate,
      startDate: defaultDate,
      startMonth: defaultMonth
    });
  },

  // 原有方法保持不变
  loadBikeInfo: function() {
    api.post(path.path.getBikeById, { id: this.data.id })
      .then(res => {
        this.setData({ bikeResource: res.data });
        this.loadOwnerInfo(res.data.createBy.id);
        this.updateMapMarkers(res.data);
        this.checkCollectionStatus();
      })
      .catch(err => console.log(err));
  },

  loadOwnerInfo: function(ownerId) {
    api.post(path.path.getUserById, { id: ownerId })
      .then(res => this.setData({ owner: res.data }))
      .catch(err => console.log(err));
  },

  updateMapMarkers: function(bikeData) {
    const markers = [...this.data.markers];
    markers[0].latitude = bikeData.latitude;
    markers[0].longitude = bikeData.longitude;
    this.setData({ markers });
  },

  checkCollectionStatus: function() {
    const userId = wx.getStorageSync('loginData').id;
    api.post(path.path.findCollectionList, {
      userId: userId,
      bikeId: this.data.bikeResource.id
    }).then(res => {
      this.setData({
        collection: res.data.length > 0,
        collectionInfo: res.data[0] || {}
      });
    }).catch(err => console.log(err));
  },

  // 租车相关方法
  toApplyRent: function() {

    const userId = wx.getStorageSync('loginData').id;
    console.log(userId);
    // 检查是否有未处理的租车申请
    api.post(path.path.getRentApplyByEntity, {
      applyUserId: userId,
      bikeId: this.data.bikeResource.id
    }).then(res => {
      if (res.data && (res.data.state === 0 || res.data.state === 1)) {
        console.log(111);
        $Toast({ content: '请先处理完该车辆的其他租赁申请' });
        return;
      }
      this.setData({ 
        rentVisiable: true,
        rentError: '',
        startMonth: '',
        endMonth: '',
        startDate: '',
        startTime: '',
        endDate: '',
        endTime: ''
      });
    })
  },

  handleRentTypeChange: function(e) {
    this.setData({ 
      rentType: e.detail.value,
      rentError: ''
    });
  },

  handleStartMonthChange: function(e) {
    this.setData({
      startMonth: e.detail.value,
      endMonth: this.data.endMonth && e.detail.value > this.data.endMonth ? '' : this.data.endMonth
    });
  },

  handleEndMonthChange: function(e) {
    this.setData({ endMonth: e.detail.value });
  },

  handleStartDateChange: function(e) {
    this.setData({
      startDate: e.detail.value,
      endDate: this.data.endDate && e.detail.value > this.data.endDate ? '' : this.data.endDate
    });
  },

  handleStartTimeChange: function(e) {
    this.setData({ startTime: e.detail.value });
  },

  handleEndDateChange: function(e) {
    this.setData({ endDate: e.detail.value });
  },

  handleEndTimeChange: function(e) {
    this.setData({ endTime: e.detail.value });
  },

  calculatePrice: function() {
    const { rentType, bikeResource, startMonth, endMonth, startDate, endDate, startTime, endTime } = this.data;
    
    if (rentType === 'long') {
      if (!startMonth || !endMonth) return 0;
      // 计算月份差
      const start = new Date(startMonth);
      const end = new Date(endMonth);
      const months = (end.getFullYear() - start.getFullYear()) * 12 + (end.getMonth() - start.getMonth()) + 1;
      return months * (bikeResource.rentingMonth || 0);
    } else {
      if (!startDate || !endDate) return 0;
      // 计算小时差
      const start = new Date(`${startDate} ${startTime || '00:00'}`);
      const end = new Date(`${endDate} ${endTime || '23:59'}`);
      const hours = Math.ceil((end - start) / (1000 * 60 * 60));
      return hours * (bikeResource.rentingHour || 0);
    }
  },

  sureRent: function() {
    const { rentType } = this.data;
    let error = '';
    
    if (rentType === 'long') {
      if (!this.data.startMonth) error = '请选择开始月份';
      else if (!this.data.endMonth) error = '请选择结束月份';
      else if (this.data.endMonth < this.data.startMonth) error = '结束月份不能早于开始月份';
    } else {
      if (!this.data.startDate) error = '请选择开始日期';
      else if (!this.data.startTime) error = '请选择开始时间';
      else if (!this.data.endDate) error = '请选择结束日期';
      else if (!this.data.endTime) error = '请选择结束时间';
      else {
        const start = new Date(`${this.data.startDate} ${this.data.startTime}`);
        const end = new Date(`${this.data.endDate} ${this.data.endTime}`);
        if (end <= start) error = '结束时间必须晚于开始时间';
      }
    }
    
    if (error) {
      this.setData({ rentError: error });
      return;
    }
    
    this.submitRentApplication();
  },
  
  submitRentApplication: function() {
    const params = {
      rentType: this.data.rentType,
      bikeId: this.data.bikeResource.id,
      applyUserId: wx.getStorageSync('loginData').id,
      state: 0
    };
    
    if (this.data.rentType === 'long') {
      params.startDate = `${this.data.startMonth}-01`;
      const [year, month] = this.data.endMonth.split('-');
      const lastDay = new Date(year, month, 0).getDate();
      params.endDate = `${this.data.endMonth}-${lastDay}`;
    } else {
      params.startDate = `${this.data.startDate} ${this.data.startTime}`;
      params.endDate = `${this.data.endDate} ${this.data.endTime}`;
    }
    
    api.post(path.path.addRentApply, params)
      .then(res => {
        if (res.code === "200") {
          $Message({
            content: '租车申请已提交，请前往申请详情页面查看',
            type: 'success'
          });
          // this.sendRentApplyNotification();
        }
        this.setData({ rentVisiable: false });
      })
      .catch(err => {
        console.log(err);
        $Toast({ content: '提交失败，请重试' });
      });
  },
  
  sendRentApplyNotification: function() {
    const params = {
      receiverType: '0',
      receiverId: this.data.bikeResource.createBy.id,
      title: '新增租车申请',
      text: baseMessage.addRentApply(),
      state: 0
    };
    api.post(path.path.addMessage, params)
      .catch(err => console.log(err));
  },

  cancelRent: function() {
    this.setData({ 
      rentVisiable: false,
      rentError: '',
      startMonth: '',
      endMonth: '',
      startDate: '',
      startTime: '',
      endDate: '',
      endTime: ''
    });
  },

  // 其他原有方法保持不变
  toApplyLook: function() {
    const userId = wx.getStorageSync('loginData').id;
    api.post(path.path.getViewApplyByEntity, {
      applyUserId: userId,
      bikeId: this.data.bikeResource.id
    }).then(res => {
      if (res.data && (res.data.state === 0 || res.data.state === 2)) {
        $Toast({ content: '请先处理完该车辆的其他看车申请' });
      } else {
        this.setData({ showModal: true });
      }
    }).catch(err => console.log(err));
  },

  modal_click_Hidden: function() {
    this.setData({ showModal: false });
  },

  bindDateChange: function(e) {
    this.setData({ viewDate: e.detail.value });
  },

  bindTimeChange: function(e) {
    this.setData({ viewTime: e.detail.value });
  },

  Sure: function() {
    const userId = wx.getStorageSync('loginData').id;
    const params = {
      applyUserId: userId,
      bikeId: this.data.bikeResource.id,
      viewTime: `${this.data.viewDate} ${this.data.viewTime}`,
      state: 0
    };
    
    api.post(path.path.addViewApply, params)
      .then(res => {
        $Message({
          content: '看车申请已提交，请前往申请页面查看详情',
          type: 'success'
        });
        this.sendViewApplyNotification();
        this.setData({ showModal: false });
      })
      .catch(err => console.log(err));
  },

  sendViewApplyNotification: function() {
    const params = {
      receiverType: '0',
      receiverId: this.data.bikeResource.createBy.id,
      title: '新增看车申请',
      text: baseMessage.addViewApply(),
      state: 0
    };
    api.post(path.path.addMessage, params)
      .catch(err => console.log(err));
  },

  collectionChange: function() {
    const userId = wx.getStorageSync('loginData').id;
    const bikeId = this.data.bikeResource.id;
    
    if (this.data.collection) {
      api.post(path.path.deleteCollection, { id: this.data.collectionInfo.id })
        .then(res => {
          if (res.code == 200) {
            $Toast({ content: '已取消收藏' });
            this.setData({ collection: false });
          }
        })
        .catch(err => console.log(err));
    } else {
      api.post(path.path.saveCollection, { bikeId, userId })
        .then(res => {
          if (res.code == 200) {
            $Toast({ content: '已成功收藏' });
            this.setData({ collection: true });
          }
        })
        .catch(err => console.log(err));
    }
  }
});